package com.kami.resolver;

import org.springframework.core.MethodParameter;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.kami.annotation.LoginUser;
import com.kami.entity.SysUser;
import com.kami.intercepter.AuthorizationInterceptor;
import com.kami.service.SysUserService;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	private SysUserService userService;//注入userService 必须与springmvc配置文件里面bean的name相同才行
	
	public void setUserService(SysUserService userService) {
		this.userService = userService;
	}
	
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(SysUser.class) && parameter.hasParameterAnnotation(LoginUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		// obj 用户id
		Object obj = webRequest.getAttribute(AuthorizationInterceptor.LOGIN_USER_KEY,RequestAttributes.SCOPE_REQUEST);
		if (obj == null) {
			return null;
		}
		
		SysUser user = userService.findOne((long)obj);
		return user;
	}

}
